package jn.chen.utils.qrCode.controller;

import jn.chen.utils.qrCode.utils.QRCodeUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @className: qrCodeController
 * @author: chenLin
 * @version: 1.0.0
 * @description:
 * @date: 2022/11/2 0002 13:50
 */
@RestController
public class qrCodeController extends QRCodeUtil {

    /**
     * 创建二维码
     * @param charSet  编码方式
     * @param content  二维码内容
     * @param qrWidth  二维码长度
     * @param qrHeight 二维码高度
     * @param fileName 二维码名称
     * @return BufferedImage
     */
    @GetMapping("/getCode")
    @ResponseBody
    public void getCode(HttpServletResponse response, String charSet, String content, int qrWidth, int qrHeight, String fileName, String topText) {
        try {
            BufferedImage image = null;
            if (topText == null){
                image = createImage(charSet, content, qrWidth, qrHeight);
            } else {
                image = createImage(charSet, content, qrWidth, qrHeight);
                addUpFont(image, topText);
            }
            File outputfile = new File("img.jpg");
            ImageIO.write(image, "jpg", outputfile);
            FileInputStream fileInputStream = new FileInputStream(outputfile);

            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename="
                    + URLEncoder.encode(fileName+".jpg", "UTF-8"));
            ServletOutputStream out = response.getOutputStream();
            IOUtils.copyLarge(fileInputStream, out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
